package androidx.pluginmgr.environment;


import android.app.Activity;
import android.app.Instrumentation;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;

import androidx.pluginmgr.PluginManager;

import java.lang.reflect.Method;

/**
 * activity的创建代理
 */
public class InstrumentationProxy extends Instrumentation {

    protected Instrumentation instrumentation;

    public InstrumentationProxy(Instrumentation instrumentation) {
        this.instrumentation = instrumentation;
    }

    public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,
                                            Intent intent, int requestCode, Bundle options) {
        Class<? extends Activity> ac = PluginManager.getSingleton().getActivitySelector().selectDynamicActivity(null);
        if (!isRegisterStubActivity(who, ac.getName())) {
            throw new ActivityNotFoundException("必须注册" + ac.getName());
        }
        //如果没有注册才替换
        if (intent.getComponent() != null) {
            String className = intent.getComponent().getClassName();
            if (!isRegisterStubActivity(who, className)) {
                intent.putExtra("realComponentName", intent.getComponent());
                intent.setComponent(new ComponentName(who, ac));
            }
        }
        Class<?>[] classes = new Class[]{Context.class, IBinder.class, IBinder.class, Activity.class, Intent.class, int.class, Bundle.class};
        try {
            Method method = getClass().getSuperclass().getDeclaredMethod("execStartActivity", classes);
            if (method != null) {
                //注意这里的obj必须用原本的Instrumentation
                return (ActivityResult) method.invoke(instrumentation, new Object[]{who, contextThread, token, target, intent, requestCode, options});
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 新建activity
     */
    @Override
    public Activity newActivity(ClassLoader cl, String className, Intent intent) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        //拿到真实的ComponentName
        ComponentName componentName = intent.getParcelableExtra("realComponentName");
        if (componentName != null) {
            className = componentName.getClassName();
        }
        return instrumentation.newActivity(cl, className, intent);
    }


    /**
     * 必须注册StubActivity
     *
     * @return 注册是否成功
     */
    private boolean isRegisterStubActivity(Context context, String activityName) {
        boolean isRegister = false;
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packageInfo;
        try {
            packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), PackageManager.GET_ACTIVITIES);
            for (ActivityInfo activity : packageInfo.activities) {
                if (activityName.equals(activity.name)) {
                    isRegister = true;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isRegister;
    }
}
